<template>
  <view class="user-space">
    <!-- 背景图 -->
    <view class="header-bg">
      <image src="/static/images/profile-bg.jpg" mode="aspectFill"></image>
      <view class="header-mask"></view>
    </view>

    <!-- 自定义导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-back" @tap="goBack">
          <uni-icons type="left" size="20" color="#fff"></uni-icons>
        </view>
        <text class="nav-title">{{ isCurrentUser ? '我的空间' : '个人主页' }}</text>
        <view class="nav-right">
          <uni-icons type="more-filled" size="24" color="#fff"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 用户信息区域 -->
    <view class="user-info" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
      <view class="user-header">
        <image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
        <view class="user-meta">
          <text class="nickname">{{ userInfo.nickname || '未知用户' }}</text>
          <text class="user-id">小红书号：{{ userInfo.id || 'unknown' }}</text>
          <text class="signature">{{ userInfo.signature || '这个人很懒，什么都没留下~' }}</text>
          <view class="user-location" v-if="userInfo.location">
            <uni-icons type="location" size="14" color="#999"></uni-icons>
            <text>{{ userInfo.location }}</text>
          </view>
        </view>
      </view>

      <!-- 用户数据统计 -->
      <view class="user-stats">
        <view class="stat-item" @tap="goPostList">
          <text class="count">{{ userInfo.postCount || 0 }}</text>
          <text class="label">笔记</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @tap="goFollowing">
          <text class="count">{{ userInfo.followingCount || 0 }}</text>
          <text class="label">关注</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @tap="goFollowers">
          <text class="count">{{ userInfo.followerCount || 0 }}</text>
          <text class="label">粉丝</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item">
          <text class="count">{{ userInfo.totalLikes || 0 }}</text>
          <text class="label">获赞</text>
        </view>
      </view>

      <!-- 操作按钮组 -->
      <view class="action-buttons" v-if="!isCurrentUser">
        <button class="primary-btn" @tap="handleFollow">
          {{ userInfo.isFollowed ? '已关注' : '关注' }}
        </button>
        <button class="secondary-btn" @tap="goChat">
          <uni-icons type="chat" size="16" color="#333"></uni-icons>
          <text>私信</text>
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 标签页 -->
      <view class="tab-bar">
        <view 
          class="tab-item"
          v-for="tab in tabs"
          :key="tab.type"
          :class="{ active: currentTab === tab.type }"
          @tap="switchTab(tab.type)"
        >
          <text>{{ tab.name }}</text>
          <view class="tab-line" v-if="currentTab === tab.type"></view>
        </view>
      </view>

      <!-- 瀑布流列表 -->
      <scroll-view 
        class="post-list" 
        scroll-y 
        @scrolltolower="loadMore"
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <view class="waterfall-container">
          <view class="waterfall-column">
            <view 
              class="post-item"
              v-for="post in leftPosts"
              :key="post.id"
              @tap="goPostDetail(post)"
            >
              <view class="image-wrap" v-if="post.images && post.images.length > 0">
                <image 
                  :src="post.images[0]"
                  mode="widthFix"
                  class="post-image"
                  @load="onImageLoad(post.id, $event)"
                ></image>
                <view class="image-count" v-if="post.images.length > 1">
                  <uni-icons type="images" size="16" color="#fff"></uni-icons>
                  <text>{{ post.images.length }}</text>
                </view>
              </view>
              <view class="post-content">
                <text class="title">{{ post.title }}</text>
                <view class="post-footer">
                  <view class="like-info">
                    <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="18" :color="post.isLiked ? '#ff4757' : '#999'"></uni-icons>
                    <text :class="{ active: post.isLiked }">{{ post.likeCount }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <view class="waterfall-column">
            <view 
              class="post-item"
              v-for="post in rightPosts"
              :key="post.id"
              @tap="goPostDetail(post)"
            >
              <view class="image-wrap" v-if="post.images && post.images.length > 0">
                <image 
                  :src="post.images[0]"
                  mode="widthFix"
                  class="post-image"
                  @load="onImageLoad(post.id, $event)"
                ></image>
                <view class="image-count" v-if="post.images.length > 1">
                  <uni-icons type="images" size="16" color="#fff"></uni-icons>
                  <text>{{ post.images.length }}</text>
                </view>
              </view>
              <view class="post-content">
                <text class="title">{{ post.title }}</text>
                <view class="post-footer">
                  <view class="like-info">
                    <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="18" :color="post.isLiked ? '#ff4757' : '#999'"></uni-icons>
                    <text :class="{ active: post.isLiked }">{{ post.likeCount }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'

export default {
  data() {
    return {
      userId: null,
      currentUserId: null,
      statusBarHeight: 0,
      userInfo: {
        nickname: '',
        avatar: '',
        postCount: 0,
        followingCount: 0,
        followerCount: 0,
        isFollowed: false
      },
      tabs: [
        { type: 'posts', name: '笔记' },
        { type: 'likes', name: '赞过' },
        { type: 'collects', name: '收藏' }
      ],
      currentTab: 'posts',
      page: 1,
      pageSize: 10,
      leftPosts: [],
      rightPosts: [],
      leftHeight: 0,
      rightHeight: 0,
      loadMoreStatus: 'more',
      isRefreshing: false,
      screenWidth: 0,
      columnWidth: 0,
      columnGap: 16
    }
  },

  computed: {
    isCurrentUser() {
      return this.userId === this.currentUserId
    }
  },

  onLoad(options) {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight
    this.screenWidth = systemInfo.windowWidth
    this.columnWidth = (this.screenWidth - 32 - this.columnGap) / 2

    // 获取用户ID
    this.userId = options.userId || null
    const userInfo = uni.getStorageSync('userInfo')
    this.currentUserId = userInfo ? userInfo.id : null

    // 如果没有传入userId且已登录，则显示当前用户的空间
    if (!this.userId && this.currentUserId) {
      this.userId = this.currentUserId
    }

    // 如果既没有userId也没有登录，跳转到登录页
    if (!this.userId) {
      uni.navigateTo({
        url: '/pages/user/auth/login'
      })
      return
    }

    // 加载用户信息和帖子列表
    this.loadUserInfo()
    this.loadPosts()
  },

  methods: {
    // 返回上一页或首页
    goBack() {
      if (this.isCurrentUser) {
        // 如果是自己的空间，返回到社区首页
        uni.switchTab({
          url: '/pages/community/index'
        })
      } else {
        // 如果是查看他人空间，返回上一页
        uni.navigateBack({
          delta: 1,
          fail: () => {
            uni.switchTab({
              url: '/pages/community/index'
            })
          }
        })
      }
    },

    // 加载帖子列表
    async loadPosts() {
      try {
        if (this.page === 1) {
          this.leftPosts = []
          this.rightPosts = []
          this.leftHeight = 0
          this.rightHeight = 0
        }

        const params = {
          userId: this.userId ? Number(this.userId) : undefined,
          pageNum: this.page,
          pageSize: this.pageSize
        }
        
        const res = await this.$api.community.posts.list(params)
        
        if (res.code === 200 && res.data) {
          const newPosts = res.data.records || []
          
          // 分配到左右列
          newPosts.forEach(post => {
            if (this.leftHeight <= this.rightHeight) {
              this.leftPosts.push(post)
              this.leftHeight += this.estimatePostHeight(post)
            } else {
              this.rightPosts.push(post)
              this.rightHeight += this.estimatePostHeight(post)
            }
          })
          
          this.loadMoreStatus = this.page >= res.data.pages ? 'noMore' : 'more'
          
          // 更新用户信息中的帖子总数
          if (this.page === 1) {
            this.userInfo = {
              ...this.userInfo,
              postCount: res.data.total || 0
            }
          }
        }
      } catch (error) {
        console.error('加载帖子列表失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    // 估算帖子高度
    estimatePostHeight(post) {
      // 根据列宽计算图片高度
      const imageHeight = post.images && post.images.length > 0 ? this.columnWidth : 0
      
      // 标题行高
      const titleHeight = 48
      
      // 内容行高
      const contentLineHeight = 20
      const contentLines = Math.ceil((post.content || '').length / 15)
      const contentHeight = contentLines * contentLineHeight
      
      // 用户信息和底部操作栏高度
      const footerHeight = 88
      
      // 内边距
      const padding = 32
      
      return imageHeight + titleHeight + contentHeight + footerHeight + padding
    },

    // 加载用户信息
    async loadUserInfo() {
      try {
        const [userRes, followRes, followingRes, followerRes] = await Promise.all([
          this.$api.community.posts.list({
            userId: this.userId ? Number(this.userId) : undefined,
            pageNum: 1,
            pageSize: 1
          }),
          // 如果不是当前用户，检查是否已关注
          !this.isCurrentUser && isLoggedIn() ? 
            this.$api.community.follow.checkIsFollowed(this.userId) : 
            Promise.resolve({ data: false }),
          // 获取关注数
          this.$api.community.follow.getFollowingList({ userId: this.userId, pageNum: 1, pageSize: 1 }),
          // 获取粉丝数
          this.$api.community.follow.getFollowerList({ userId: this.userId, pageNum: 1, pageSize: 1 })
        ])
        
        if (userRes.code === 200 && userRes.data) {
          // 从第一条帖子中获取用户信息
          const firstPost = userRes.data.records?.[0]
          if (firstPost) {
            this.userInfo = {
              ...this.userInfo,
              nickname: firstPost.userNickname || '',
              avatar: firstPost.userAvatar || '',
              postCount: userRes.data.total || 0,
              // 设置关注状态
              isFollowed: followRes.code === 200 ? followRes.data : false,
              // 设置关注数和粉丝数
              followingCount: followingRes.code === 200 ? followingRes.data.total : 0,
              followerCount: followerRes.code === 200 ? followerRes.data.total : 0
            }
          }
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        uni.showToast({
          title: error.message || '加载用户信息失败',
          icon: 'none'
        })
      }
    },

    // 切换标签
    switchTab(tab) {
      if (this.currentTab === tab) return
      this.currentTab = tab
      this.page = 1
      this.leftPosts = []
      this.rightPosts = []
      this.leftHeight = 0
      this.rightHeight = 0
      this.loadPosts()
    },

    // 图片加载完成
    onImageLoad(postId, event) {
      const imageWidth = this.columnWidth
      const imageHeight = event.detail.height * (imageWidth / event.detail.width)
      
      // 更新列高度
      const post = [...this.leftPosts, ...this.rightPosts].find(p => p.id === postId)
      if (post) {
        const isLeftColumn = this.leftPosts.includes(post)
        if (isLeftColumn) {
          this.leftHeight += imageHeight
        } else {
          this.rightHeight += imageHeight
        }
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.page = 1
      await Promise.all([
        this.loadUserInfo(),
        this.loadPosts()
      ])
      this.isRefreshing = false
    },

    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'more') {
        this.page++
        this.loadPosts()
      }
    },

    // 跳转到帖子详情
    goPostDetail(post) {
      uni.navigateTo({
        url: `/pages/community/detail/index?id=${post.id}`
      })
    },

    // 处理关注/取消关注
    async handleFollow() {
      if (!isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      try {
        if (this.userInfo.isFollowed) {
          await this.$api.community.follow.unfollowUser(this.userId)
          this.userInfo.isFollowed = false
          this.userInfo.followerCount--
          uni.showToast({
            title: '已取消关注',
            icon: 'success'
          })
        } else {
          await this.$api.community.follow.followUser(this.userId)
          this.userInfo.isFollowed = true
          this.userInfo.followerCount++
          uni.showToast({
            title: '关注成功',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('关注操作失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    },

    // 跳转到关注列表
    goFollowing() {
      uni.navigateTo({
        url: `/pages/community/following/index?userId=${this.userId}`
      })
    },
    
    // 跳转到粉丝列表
    goFollowers() {
      uni.navigateTo({
        url: `/pages/community/followers/index?userId=${this.userId}`
      })
    },

    // 跳转到聊天页面
    goChat() {
      if (!isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/user/message/chat-detail?userId=${this.userId}&nickname=${encodeURIComponent(this.userInfo.nickname)}&avatar=${encodeURIComponent(this.userInfo.avatar)}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-space {
  min-height: 100vh;
  background-color: #fff;
}

.header-bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  z-index: 1;
  
  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .header-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(180deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.1) 100%);
  }
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  
  .nav-content {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    padding: 0 15px;
    
    .nav-back {
      padding: 10px;
      margin-left: -10px;
    }
    
    .nav-title {
      font-size: 16px;
      font-weight: 500;
      color: #fff;
    }
    
    .nav-right {
      padding: 10px;
      margin-right: -10px;
    }
  }
}

.user-info {
  position: relative;
  z-index: 2;
  padding: 30rpx;
  background: linear-gradient(180deg, transparent 0%, #fff 100%);
  
  .user-header {
    margin-bottom: 40rpx;
    
    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      border: 6rpx solid #fff;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
      margin-bottom: 24rpx;
    }
    
    .user-meta {
      .nickname {
        font-size: 40rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 12rpx;
        display: block;
      }
      
      .user-id {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 16rpx;
        display: block;
      }
      
      .signature {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
        margin-bottom: 16rpx;
        display: block;
      }
      
      .user-location {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #999;
        
        text {
          margin-left: 6rpx;
        }
      }
    }
  }
  
  .user-stats {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 0;
    margin-bottom: 30rpx;
    
    .stat-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .count {
        font-size: 36rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .label {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .stat-divider {
      width: 2rpx;
      height: 40rpx;
      background: #eee;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    
    button {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &.primary-btn {
        background: linear-gradient(45deg, #ff4757, #ff6b81);
        color: #fff;
        
        &:active {
          opacity: 0.9;
        }
      }
      
      &.secondary-btn {
        background: #f8f8f8;
        color: #333;
        
        text {
          margin-left: 8rpx;
        }
        
        &:active {
          background: #f0f0f0;
        }
      }
    }
  }
}

.content-area {
  position: relative;
  z-index: 2;
  background: #fff;
  min-height: 60vh;
  border-radius: 32rpx 32rpx 0 0;
  margin-top: -32rpx;
  overflow: hidden;
  
  .tab-bar {
    display: flex;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .tab-item {
      position: relative;
      padding: 24rpx 40rpx;
      
      text {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
      }
      
      &.active {
        text {
          color: #333;
          font-weight: bold;
        }
        
        .tab-line {
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background: #ff4757;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .post-list {
    height: calc(100vh - 600rpx);
    
    .waterfall-container {
      display: flex;
      padding: 20rpx;
      gap: 20rpx;
      
      .waterfall-column {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20rpx;
      }
    }
    
    .post-item {
      background: #fff;
      border-radius: 16rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
      
      .image-wrap {
        position: relative;
        width: 100%;
        
        .post-image {
          width: 100%;
          border-radius: 16rpx 16rpx 0 0;
        }
        
        .image-count {
          position: absolute;
          top: 16rpx;
          right: 16rpx;
          background: rgba(0, 0, 0, 0.3);
          border-radius: 24rpx;
          padding: 4rpx 12rpx;
          display: flex;
          align-items: center;
          
          text {
            color: #fff;
            font-size: 24rpx;
            margin-left: 4rpx;
          }
        }
      }
      
      .post-content {
        padding: 20rpx;
        
        .title {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          @include text-ellipsis(2);
          margin-bottom: 16rpx;
        }
        
        .post-footer {
          display: flex;
          align-items: center;
          justify-content: space-between;
          
          .like-info {
            display: flex;
            align-items: center;
            gap: 6rpx;
            
            text {
              font-size: 24rpx;
              color: #999;
              
              &.active {
                color: #ff4757;
              }
            }
          }
        }
      }
    }
  }
}
</style> 